package com.lst.tools.redis.config;

import com.lst.tools.redis.constant.RedisConstants;
import com.lst.tools.redis.properties.RedisPoolProperties;
import com.lst.tools.redis.properties.RedisSentinelProperties;
import com.lst.tools.redis.properties.RedisSingleProperties;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.util.Pool;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * redis缓存连接配置
 *
 * @author: Frank
 * @date: 2019/09/24 13:51
 * @version: V1.0
 */
@Configuration
public class RedisCacheConfig extends CachingConfigurerSupport {

    @Autowired
    private RedisPoolProperties redisPoolProperties;
    @Autowired
    private RedisSentinelProperties redisSentinelProperties;
    @Autowired
    private RedisSingleProperties redisSingleProperties;

    /**
     * redis哨兵配置
     *
     * @return
     */
    @Bean
    public GenericObjectPoolConfig poolConfig() {
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(redisPoolProperties.getMaxTotal());
        poolConfig.setMaxIdle(redisPoolProperties.getMaxIdle());
        poolConfig.setMinIdle(redisPoolProperties.getMinIdle());
        return poolConfig;
    }

    /**
     * 连接redis的连接池
     *
     * @return
     */
    @Bean
    public Pool<Jedis> pool() {
        String mode = redisPoolProperties.getMode();
        if (RedisConstants.MODE_SINGLE.equalsIgnoreCase(mode)) {
            return new JedisPool(poolConfig(),
                    redisSingleProperties.getHost(),
                    redisSingleProperties.getPort(),
                    redisSingleProperties.getTimeout(),
                    redisSingleProperties.getPassword(),
                    redisSingleProperties.getDatabase());
        } else if (RedisConstants.MODE_SENTINEL.equalsIgnoreCase(mode)) {
            Set<String> sentinels = new HashSet<String>(Arrays.asList(redisSentinelProperties.getNodes().split(RedisConstants.NODE_SPLIT)));
            return new JedisSentinelPool(
                    redisSentinelProperties.getMaster(),
                    sentinels,
                    poolConfig(),
                    redisSentinelProperties.getTimeout(),
                    redisSentinelProperties.getPassword(),
                    redisSentinelProperties.getDatabase()
            );
        }
        return null;
    }
}
